#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   email_module.py
@Time    :   2024/02/06 07:31:03
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   发送邮件
'''

import smtplib
from email.mime.text import MIMEText
from email.header import Header
import base64

# 电子邮件类（仅QQ邮箱）
class Mail:
    def __init__(self, mail_host:str, mail_pass:str, sender:str, receivers:list):
        # 第三方 SMTP 服务
        self.mail_host = mail_host # 填写邮箱服务器:这个是qq邮箱服务器，直接使用smtp.qq.com
        self.mail_pass = mail_pass # 填写在qq邮箱设置中获取的授权码
        self.sender = sender  # 填写发送方邮箱地址
        self.receivers = receivers  # 填写收件人的邮箱，QQ邮箱或者其他邮箱，可多个，中间用,隔开

    def send(self, subject, txt):
        # subject = '预订成功'  # 发送的主题
        content = str(txt)   #邮件内容
        message = MIMEText(content, 'plain', 'utf-8')
        message['From'] = Header(f'=?utf-8?B?{base64.b64encode("python自动发送".encode()).decode()}=?= <{self.sender}>')      #必须填发送者邮箱
        message['To'] = Header("rpa自动发送", 'utf-8')    #邮件接收者姓名
        message['Subject'] = Header(subject, 'utf-8')
        try:
            smtpObj = smtplib.SMTP_SSL(self.mail_host, 465) #建立smtp连接，qq邮箱必须用ssl边接，因此边接465端口
            smtpObj.login(self.sender, self.mail_pass)  #登陆
            smtpObj.sendmail(self.sender, self.receivers, message.as_string())  #发送
            smtpObj.quit()
            print('邮件发送成功！！')
        except smtplib.SMTPException as e:
            print(e.__traceback__.tb_lineno,e)
            print('邮件发送失败！！')
            
if __name__ == '__main__':
    mail = Mail("smtp.qq.com", 'qiljvbiizqofbfgb', 'chakcy1212@qq.com', ['chakcy1212@qq.com'])
    mail.send('测试', '发送内容')
